﻿using Studio77.RuneMaster.Core;
using Studio77.RuneMaster.Entities;
using Studio77.RuneMaster.Entities.GameRecord;
using Studio77.RuneMaster.Pages;
using Studio77.RuneMaster.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace Studio77.RuneMaster.Views
{
    public class RuneGameCanvas : Canvas
    {
        int[,] datas = new int[GameStatics.RowCount, GameStatics.ColumnCount];
        RuneItem[,] runes = new RuneItem[GameStatics.RowCount, GameStatics.ColumnCount];
        RuneItem selectedItem = null;
        List<RuneItem> spriteRunes = new List<RuneItem>();
        int selectRow = -1, selectColumn = -1;
        Random r = new Random(DateTime.Now.Millisecond);

        bool isElimition = false;
        object isElimitionSyncObj = new object();

        ScoreView scoreView = new ScoreView();

        int currentCombo = 1;

        public RuneGameCanvas()
        {
            this.MouseLeftButtonDown += gameCanvas_MouseLeftButtonDown;
            this.ManipulationStarted += RuneGameCanvas_ManipulationStarted;
            this.ManipulationCompleted += RuneGameCanvas_ManipulationCompleted;
        }


        #region 滑动处理

        bool isStartManipulation = false;
        int manipulationRow = -1;
        int manipulationColumn = -1;

       void RuneGameCanvas_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
        {
            if (isStartManipulation)
            {
                isStartManipulation = false;
                //方向
                int dirction = GetManipulationDirection(e.TotalManipulation.Translation);

                //判断能否移动
                if (dirction != 0)
                {
                    ManipulationMove(manipulationRow, manipulationColumn, dirction);
                }
            }
        }

        //手势移动
        private void ManipulationMove(int manipulationRow, int manipulationColumn, int dirction)
        {
            int aimColumn = -1, aimRow = -1;
            switch (dirction)
            {
                case 1:
                    //向左
                    aimRow = manipulationRow;
                    aimColumn = manipulationColumn - 1;
                    break;
                case 2:
                    //左上
                    aimRow = manipulationRow - 1;
                    aimColumn = manipulationColumn - 1;
                    break;
                case 3:
                    //上
                    aimRow = manipulationRow - 1;
                    aimColumn = manipulationColumn;
                    break;
                case 4:
                    //右上
                    aimRow = manipulationRow - 1;
                    aimColumn = manipulationColumn + 1;
                    break;
                case 5:
                    //右
                    aimRow = manipulationRow;
                    aimColumn = manipulationColumn + 1;
                    break;
                case 6:
                    //右下
                    aimRow = manipulationRow + 1;
                    aimColumn = manipulationColumn + 1;
                    break;
                case 7:
                    //下
                    aimRow = manipulationRow + 1;
                    aimColumn = manipulationColumn;
                    break;
                case 8:
                    //左下
                    aimRow = manipulationRow + 1;
                    aimColumn = manipulationColumn - 1;
                    break;
            }
            if ((aimRow >= 0 && aimRow < GameStatics.RowCount && aimColumn >= 0 && aimColumn < GameStatics.ColumnCount)
                && (runes[aimRow, aimColumn] != null && runes[aimRow, aimColumn].IsRuneEnable
                        && datas[aimRow, aimColumn] != datas[manipulationRow, manipulationColumn] &&
                       ((aimRow == manipulationRow && Math.Abs(aimColumn - manipulationColumn) == 1)
                       || (aimColumn == manipulationColumn && Math.Abs(aimRow - manipulationRow) == 1)
                       || (aimRow != manipulationRow && aimColumn != manipulationColumn) && (Math.Abs(aimRow - manipulationRow) == 1 && Math.Abs(aimColumn - manipulationColumn) == 1))))
            {

                //同步使用
                lock (isElimitionSyncObj)
                {
                    if (isElimition)
                    {
                        return;
                    }
                }

                //清空选中
                if (selectedItem != null)
                {
                    selectedItem.UnSelect();
                }
                selectedItem = null;
                selectRow = -1;
                selectColumn = -1;

                //可以进行移动
                //减少精神力
                GamePage.Instance.SubSprite();

                //记录游戏移动次数
                StageManager.Instance.GameHightlightsRecord.TotalMove++;

                //互换位置，同时清空选中
                RuneItemChangeInfo change = new RuneItemChangeInfo()
                {
                    EndX = manipulationRow,
                    EndY = manipulationColumn,
                    StartX = aimRow,
                    StartY = aimColumn
                };
                double delay = ExchangeRune(change);
                //交换数据
                int temp = datas[manipulationRow, manipulationColumn];
                datas[manipulationRow, manipulationColumn] = datas[aimRow, aimColumn];
                datas[aimRow, aimColumn] = temp;

                RuneItem tempRune = runes[manipulationRow, manipulationColumn];
                runes[manipulationRow, manipulationColumn] = runes[aimRow, aimColumn];
                runes[aimRow, aimColumn] = tempRune;

                DispatcherTimer timer = new DispatcherTimer();
                timer.Interval = TimeSpan.FromMilliseconds(delay);
                timer.Tick += (object sender2, EventArgs ee) =>
                {
                    timer.Stop();
                    EliminateStatus status = new EliminateStatus();
                    List<RuneItemChangeInfo> needToEliminate = EliminateLogicHelper.FindEliminate(datas, ref status);
                    if (needToEliminate.Count > 0)
                    {
                        lock (isElimitionSyncObj)
                        {
                            isElimition = true;
                        }
                        ProcessEliminate(needToEliminate, status);
                    }
                    else
                    {
                        SubSpriteRunePower();

                        //清除道具并更新界面
                        StageManager.Instance.ClearUsedTool();
                        GamePage.Instance.UpdateUsedToolUI();

                        //检查游戏状态
                        GamePage.Instance.JudgeSuccessFail();
                    }

                };
                timer.Start();
            }
        }

        /// <summary>
        /// 0-none 1-左 2-左上 3-上 4-右上 5-右 6-右下 7-下 8-左下
        /// </summary>
        /// <param name="point"></param>
        private int GetManipulationDirection(Point point)
        {
            int result = 0;
            //首先判断移动距离，如果距离在范围内，在判断角度
            double distance = Math.Sqrt(Math.Abs(point.X) * Math.Abs(point.X) + Math.Abs(point.Y) * Math.Abs(point.Y));
            if (distance > GameStatics.ItemSize / 2 && distance < GameStatics.ItemSize * 3)
            {
                if (point.X < -GameStatics.ItemSize / 2 && Math.Abs(point.Y) < GameStatics.ItemSize / 2)
                {
                    result = 1;
                }
                if (point.X < -GameStatics.ItemSize / 2 && point.Y < -GameStatics.ItemSize / 2)
                {
                    result = 2;
                }
                if (point.X < -GameStatics.ItemSize / 2 && point.Y > GameStatics.ItemSize / 2)
                {
                    result = 8;
                }
                if (point.Y < -GameStatics.ItemSize / 2 && Math.Abs(point.X) < GameStatics.ItemSize / 2)
                {
                    result = 3;
                }
                if (point.Y < -GameStatics.ItemSize / 2 && point.X > GameStatics.ItemSize / 2)
                {
                    result = 4;
                }
                if (point.X > GameStatics.ItemSize / 2 && Math.Abs(point.Y) < GameStatics.ItemSize / 2)
                {
                    result = 5;
                }
                if (point.X > GameStatics.ItemSize / 2 && point.Y > GameStatics.ItemSize / 2)
                {
                    result = 6;
                }
                if (point.Y > GameStatics.ItemSize / 2 && Math.Abs(point.X) < GameStatics.ItemSize / 2)
                {
                    result = 7;
                }
            }
            return result;

        }

       void RuneGameCanvas_ManipulationStarted(object sender, System.Windows.Input.ManipulationStartedEventArgs e)
        {
            if (!isStartManipulation)
            {
                isStartManipulation = true;
                Point p = e.ManipulationOrigin;
                manipulationColumn = (int)p.X / GameStatics.ItemSize;
                manipulationRow = (int)p.Y / GameStatics.ItemSize;
            }
        }

        #endregion

        /// <summary>
        /// 开始全新游戏
        /// </summary>
        public void InitGame()
        {
            spriteRunes.Clear();
            this.Children.Clear();
            selectRow = -1;
            selectColumn = -1;
            isElimition = false;
            selectedItem = null;


            //初始化
            for (int i = 0; i < GameStatics.RowCount; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount; j++)
                {
                    datas[i, j] = 0;
                    runes[i, j] = null;
                }
            }

            for (int i = 0; i < GameStatics.RowCount; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount; j++)
                {
                    //需要判断保证一开始不能有能直接消除的东西
                    RuneItem item = new RuneItem();
                    int type = r.Next(5) + 1;
                    datas[i, j] = type;
                    while (EliminateLogicHelper.IsCanEliminate(datas))
                    {
                        type = r.Next(5) + 1;
                        datas[i, j] = type;
                    }
                    item.SetType(type);
                    Canvas.SetTop(item, i * GameStatics.ItemSize);
                    Canvas.SetLeft(item, j * GameStatics.ItemSize);
                    runes[i, j] = item;
                    this.Children.Add(item);
                }
            }
            Canvas.SetTop(scoreView, 280 - scoreView.Height / 2);
            Canvas.SetLeft(scoreView, 200 - scoreView.Width / 2);
            Canvas.SetZIndex(scoreView, 3);
            scoreView.Visibility = System.Windows.Visibility.Collapsed;

            this.Children.Add(scoreView);
        }

        /// <summary>
        /// 载入历史游戏进度
        /// </summary>
        /// <param name="list"></param>
        internal void InitGame(List<SavedRune> runeRecords)
        {
            spriteRunes.Clear();
            this.Children.Clear();
            selectRow = -1;
            selectColumn = -1;
            isElimition = false;
            selectedItem = null;

            //初始化
            for (int i = 0; i < GameStatics.RowCount; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount; j++)
                {
                    datas[i, j] = 0;
                    runes[i, j] = null;
                }
            }

            foreach (var rr in runeRecords)
            {
                RuneItem item = new RuneItem();
                datas[rr.X, rr.Y] = rr.RuneType;
                item.SetType(rr.RuneType);
                Canvas.SetTop(item, rr.X * GameStatics.ItemSize);
                Canvas.SetLeft(item, rr.Y * GameStatics.ItemSize);
                runes[rr.X, rr.Y] = item;
                if (rr.LeftSpriteCount > 0)
                {
                    item.SetSpriteAddRune(rr.LeftSpriteCount);
                }
                this.Children.Add(item);
            }

            Canvas.SetTop(scoreView, 280 - scoreView.Height / 2);
            Canvas.SetLeft(scoreView, 200 - scoreView.Width / 2);
            Canvas.SetZIndex(scoreView, 3);
            scoreView.Visibility = System.Windows.Visibility.Collapsed;

            this.Children.Add(scoreView);
        }

        void gameCanvas_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            //同步使用
            lock (isElimitionSyncObj)
            {
                if (isElimition)
                {
                    return;
                }
            }

            //判断点击的位置，并进行操作

            //获取行列
            Point postion = e.GetPosition(this);
            int row = (int)postion.Y / GameStatics.ItemSize;
            int column = (int)postion.X / GameStatics.ItemSize;

            if (row < 7 && column < 5)
            {
                if (selectedItem == null)
                {
                    if (runes[row, column] != null && runes[row, column].IsRuneEnable)
                    {
                        SoundManager.PlayEffect(SoundManager.runeClick);
                        //直接选中
                        runes[row, column].Select();
                        selectedItem = runes[row, column];
                        selectRow = row;
                        selectColumn = column;
                    }
                }
                else if (selectedItem != runes[row, column])
                {
                    //之前有选中的，判断是否能够调换
                    if (runes[row, column] != null && runes[row, column].IsRuneEnable
                         && datas[row, column] != datas[selectRow, selectColumn] &&
                        ((row == selectRow && Math.Abs(column - selectColumn) == 1)
                        || (column == selectColumn && Math.Abs(row - selectRow) == 1)
                        || (row != selectRow && column != selectColumn) && (Math.Abs(row - selectRow) == 1 && Math.Abs(column - selectColumn) == 1)))
                    {
                        //减少精神力
                        GamePage.Instance.SubSprite();

                        //记录游戏移动次数
                        StageManager.Instance.GameHightlightsRecord.TotalMove++;

                        //互换位置，同时清空选中
                        RuneItemChangeInfo change = new RuneItemChangeInfo()
                        {
                            StartX = row,
                            StartY = column,
                            EndX = selectRow,
                            EndY = selectColumn
                        };
                        double delay = ExchangeRune(change);
                        //交换数据
                        int temp = datas[row, column];
                        datas[row, column] = datas[selectRow, selectColumn];
                        datas[selectRow, selectColumn] = temp;

                        RuneItem tempRune = runes[row, column];
                        runes[row, column] = runes[selectRow, selectColumn];
                        runes[selectRow, selectColumn] = tempRune;

                        DispatcherTimer timer = new DispatcherTimer();
                        timer.Interval = TimeSpan.FromMilliseconds(delay);
                        timer.Tick += (object sender2, EventArgs ee) =>
                        {
                            timer.Stop();
                            EliminateStatus status = new EliminateStatus();
                            List<RuneItemChangeInfo> needToEliminate = EliminateLogicHelper.FindEliminate(datas, ref status);
                            if (needToEliminate.Count > 0)
                            {
                                lock (isElimitionSyncObj)
                                {
                                    isElimition = true;
                                }
                                ProcessEliminate(needToEliminate, status);
                            }
                            else
                            {
                                SubSpriteRunePower();

                                //清除道具并更新界面
                                StageManager.Instance.ClearUsedTool();
                                GamePage.Instance.UpdateUsedToolUI();

                                //检查游戏状态
                                GamePage.Instance.JudgeSuccessFail();
                            }

                        };
                        timer.Start();

                        //清空选中
                        selectedItem.UnSelect();
                        selectedItem = null;
                        selectRow = -1;
                        selectColumn = -1;
                    }
                    else
                    {
                        //不能互换，选择新的
                        SoundManager.PlayEffect(SoundManager.runeClick);
                        selectedItem.UnSelect();
                        runes[row, column].Select();
                        selectedItem = runes[row, column];
                        selectRow = row;
                        selectColumn = column;
                    }
                }
                else
                {
                    SoundManager.PlayEffect(SoundManager.runeClick);
                    selectedItem.UnSelect();
                    selectedItem = null;
                    selectRow = -1;
                    selectColumn = -1;
                }

            }

        }

        /// <summary>
        /// 判断符文是否被处理过
        /// </summary>
        List<int> tempKeys = new List<int>();
        int lastDuplex = 0;
        int scoreInThisTurn = 0;

        /// <summary>
        /// 处理需要消除的
        /// </summary>
        /// <param name="needToEliminate"></param>
        private void ProcessEliminate(List<RuneItemChangeInfo> needToEliminate, EliminateStatus status)
        {
            int score = ScoreHelper.CalScore(status, currentCombo);

            scoreInThisTurn += score;

            scoreView.Visibility = System.Windows.Visibility.Visible;
            Dictionary<int, int> duplexs = ScoreHelper.CalRuneDuplex(status);

            if (currentCombo > 1)
            {
                GamePage.Instance.AddCombo();

                //记录Combo次数
                StageManager.Instance.GameHightlightsRecord.TotalCombo++;
            }

            if (duplexs.Values.Max() > lastDuplex)
            {
                lastDuplex = duplexs.Values.Max();
            }
            scoreView.ShowScore(score, duplexs.Values.Max(), currentCombo);

            //消除的音效
            int comboId = SoundManager.eliminate1 + currentCombo - 1;
            if (comboId > SoundManager.eliminate6)
            {
                comboId = SoundManager.eliminate6;
            }
            SoundManager.PlayEffect(comboId);

            //记录分数
            GamePage.Instance.AddScore(score);

            //判断是否有新增精神力的符文，并进行处理
            tempKeys.Clear();
            foreach (var ele in needToEliminate)
            {
                int key = ele.StartX * GameStatics.ColumnCount + ele.StartY;
                if (!tempKeys.Contains(key))
                {
                    tempKeys.Add(key);
                    RuneItem rune = runes[ele.StartX, ele.StartY];
                    if (rune.IsSpriteAddRune())
                    {
                        int baseValue = 1;
                        if (StageManager.Instance.CurrentUsedTool.ContainsValue(ToolType.SpriteMutil2))
                        {
                            baseValue = 2;
                        }
                        rune.FlyAddSpriteFlag(duplexs[rune.Type] * baseValue);
                        spriteRunes.Remove(rune);
                    }
                }
            }

            List<int> columns = new List<int>();
            double eliminateDelay = 700;
            foreach (var eliminateItem in needToEliminate)
            {
                if (!columns.Contains(eliminateItem.StartY))
                {
                    columns.Add(eliminateItem.StartY);
                }
                //消除
                RuneItem rune = runes[eliminateItem.StartX, eliminateItem.StartY];
                if (rune.IsRuneEnable)
                {
                    Canvas.SetZIndex(rune, 2);
                    eliminateDelay = rune.Eliminate();
                    //清空数据
                    datas[eliminateItem.StartX, eliminateItem.StartY] = 0;
                    runes[eliminateItem.StartX, eliminateItem.StartY].IsRuneEnable = false;
                }
            }

            //移动现有数据
            DispatcherTimer timerMove = new DispatcherTimer();
            timerMove.Interval = TimeSpan.FromMilliseconds(eliminateDelay);
            timerMove.Tick += (object sender2, EventArgs ee) =>
            {
                scoreView.Visibility = System.Windows.Visibility.Collapsed;
                timerMove.Stop();
                double maxMSconds = 0;
                foreach (int column in columns)
                {
                    double temp = MoveBottom(column);
                    if (temp > maxMSconds)
                    {
                        maxMSconds = temp;
                    }
                }

                //增加符文
                //DispatcherTimer timerAddRune = new DispatcherTimer();
                //timerAddRune.Interval = TimeSpan.FromMilliseconds(maxMSconds);
                //timerAddRune.Tick += (object sender3, EventArgs eee) =>
                //{
                //timerAddRune.Stop();
                AddNewRenu();

                //};
                //timerAddRune.Start();

            };
            timerMove.Start();
        }

        private void AddNewRenu()
        {
            int maxColumnBlank = 0;
            int columnBlank = 0;
            //增加新的符文
            for (int j = 0; j < GameStatics.ColumnCount; j++)
            {
                for (int i = 0; i < GameStatics.RowCount; i++)
                {
                    if (i == 0)
                    {
                        columnBlank = 0;
                        //计算每一列的空缺
                        for (int k = 0; k < GameStatics.RowCount; k++)
                        {
                            if (datas[k, j] == 0)
                            {
                                columnBlank++;
                            }
                        }
                    }
                    if (datas[i, j] == 0)
                    {
                        if (columnBlank > maxColumnBlank)
                        {
                            maxColumnBlank = columnBlank;
                        }
                        //补数据
                        datas[i, j] = r.Next(5) + 1;
                        runes[i, j].SetType(datas[i, j]);
                        runes[i, j].Show(columnBlank);

                        //重新设置位置
                        Canvas.SetTop(runes[i, j], i * GameStatics.ItemSize);
                        Canvas.SetLeft(runes[i, j], j * GameStatics.ItemSize);
                    }
                }
            }

            EliminateStatus status = new EliminateStatus();
            List<RuneItemChangeInfo> finds = EliminateLogicHelper.FindEliminate(datas, ref status);
            if (finds.Count == 0)
            {

                DispatcherTimer spriteRuneProcessTimer = new DispatcherTimer();
                spriteRuneProcessTimer.Interval = TimeSpan.FromMilliseconds(GameStatics.RuneDownSpeed * maxColumnBlank + 50);
                spriteRuneProcessTimer.Tick += (object sender2, EventArgs ee) =>
                {
                    spriteRuneProcessTimer.Stop();
                    SubSpriteRunePower();
                    //增加N个精神力符文
                    for (int i = 0; i < lastDuplex; i++)
                    {
                        int toolRow = r.Next(GameStatics.RowCount);
                        int toolColumn = r.Next(GameStatics.ColumnCount);
                        int findCount = 1;

                        while (runes[toolRow, toolColumn].IsSpriteAddRune() && findCount < 5)
                        {
                            toolRow = r.Next(GameStatics.RowCount);
                            toolColumn = r.Next(GameStatics.ColumnCount);
                        }

                        if (!runes[toolRow, toolColumn].IsSpriteAddRune())
                        {
                            //设置成为精神力符文
                            runes[toolRow, toolColumn].SetSpriteAddRune();
                            spriteRunes.Add(runes[toolRow, toolColumn]);

                            SoundManager.PlayEffect(SoundManager.addSpiritRune);
                        }
                    }
                    lastDuplex = 0;

                    //检查游戏状态
                    GamePage.Instance.JudgeSuccessFail();

                };
                spriteRuneProcessTimer.Start();

                //单次移动最高积分
                if (StageManager.Instance.GameHightlightsRecord.HighScoreIn1 < scoreInThisTurn)
                {
                    StageManager.Instance.GameHightlightsRecord.HighScoreIn1 = scoreInThisTurn;
                }

                //总分逻辑
                StageManager.Instance.GameHightlightsRecord.TotalScore += scoreInThisTurn;

                //重置本次分数统计
                scoreInThisTurn = 0;

                //最高Combo
                if ((currentCombo - 1) > StageManager.Instance.GameHightlightsRecord.MaxCombo)
                {
                    StageManager.Instance.GameHightlightsRecord.MaxCombo = currentCombo - 1;
                }

                //重置连击状态
                currentCombo = 1;

                //清除道具并更新界面
                StageManager.Instance.ClearUsedTool();
                GamePage.Instance.UpdateUsedToolUI();

                //设置为可操作状态
                lock (isElimitionSyncObj)
                {
                    isElimition = false;
                }
            }
            else
            {
                currentCombo++;
                DispatcherTimer nextProcessTimer = new DispatcherTimer();
                nextProcessTimer.Interval = TimeSpan.FromMilliseconds(GameStatics.RuneDownSpeed * maxColumnBlank + 50);
                nextProcessTimer.Tick += (object sender2, EventArgs ee) =>
                {
                    nextProcessTimer.Stop();
                    ProcessEliminate(finds, status);
                };
                nextProcessTimer.Start();

            }

        }

        /// <summary>
        /// 减少精神力符文的力量
        /// </summary>
        private void SubSpriteRunePower()
        {
            List<RuneItem> deleteList = new List<RuneItem>();
            foreach (var item in spriteRunes)
            {
                item.SubSpriteAddLeftCount();
                if (!item.IsSpriteAddRune())
                {
                    deleteList.Add(item);
                }
            }
            foreach (var item in deleteList)
            {
                spriteRunes.Remove(item);
            }
        }

        /// <summary>
        /// 向下移动
        /// </summary>
        /// <param name="column"></param>
        /// <returns></returns>
        private double MoveBottom(int column)
        {
            double result = 0;
            List<RuneItemChangeInfo> needToExchange = new List<RuneItemChangeInfo>();

            // 找到一个空的，往后寻找，找到替换，没找到break
            for (int i = GameStatics.RowCount - 1; i >= 0; i--)
            {
                int data = datas[i, column];
                if (data == 0)
                {
                    RuneItemChangeInfo findInfo = new RuneItemChangeInfo();
                    findInfo.StartX = -1;
                    findInfo.StartY = -1;
                    findInfo.EndX = -1;
                    findInfo.EndY = -1;

                    for (int ii = i - 1; ii >= 0; ii--)
                    {
                        int tempData = datas[ii, column];
                        if (tempData > 0)
                        {
                            findInfo.EndX = i;
                            findInfo.EndY = column;
                            findInfo.StartX = ii;
                            findInfo.StartY = column;
                            break;
                        }
                    }
                    if (findInfo.StartX != -1 && findInfo.EndX != -1)
                    {
                        //更新datas
                        int temp = datas[findInfo.StartX, findInfo.StartY];
                        datas[findInfo.StartX, findInfo.StartY] = datas[findInfo.EndX, findInfo.EndY];
                        datas[findInfo.EndX, findInfo.EndY] = temp;
                        needToExchange.Add(findInfo);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            // 互换并更新界面
            result = ExchangeRune(needToExchange, false);

            foreach (var findInfo in needToExchange)
            {
                //更新runes
                RuneItem runetemp = runes[findInfo.StartX, findInfo.StartY];
                runes[findInfo.StartX, findInfo.StartY] = runes[findInfo.EndX, findInfo.EndY];
                runes[findInfo.EndX, findInfo.EndY] = runetemp;
            }

            return result;
        }



        private double ExchangeRune(RuneItemChangeInfo info)
        {
            List<RuneItemChangeInfo> lst = new List<RuneItemChangeInfo>();
            lst.Add(info);
            RuneItemChangeInfo info2 = new RuneItemChangeInfo()
            {
                StartX = info.EndX,
                StartY = info.EndY,
                EndX = info.StartX,
                EndY = info.StartY
            };
            lst.Add(info2);

            return ExchangeRune(lst, true);
        }

        /// <summary>
        /// 交换符文
        /// </summary>
        /// <param name="needToExchange"></param>
        /// <param name="isOp"></param>
        /// <returns>返回动画结束的毫秒信息</returns>
        private double ExchangeRune(List<RuneItemChangeInfo> needToExchange, bool isOp)
        {
            double maxDuration = 0;
            foreach (var item in needToExchange)
            {
                //做动画改变位置
                RuneItem rune = runes[item.StartX, item.StartY];
                if (rune.IsRuneEnable)
                {
                    Storyboard storyBoard = new Storyboard();
                    double durations = GetDuration(item, isOp);
                    Duration duration = new Duration(TimeSpan.FromMilliseconds(durations));

                    if (durations > maxDuration)
                    {
                        maxDuration = durations;
                    }

                    DoubleAnimation daX = new DoubleAnimation();
                    daX.Duration = duration;
                    daX.To = item.EndX * GameStatics.ItemSize;
                    DoubleAnimation daY = new DoubleAnimation();
                    daY.Duration = duration;
                    daY.To = item.EndY * GameStatics.ItemSize;

                    if (!isOp)
                    {
                        //弹跳
                        QuadraticEase bounce = new QuadraticEase();
                        bounce.EasingMode = EasingMode.EaseIn;
                        //bounce.Bounces = 2;
                        //bounce.Bounciness = 5;
                        daX.EasingFunction = bounce;
                        daY.EasingFunction = bounce;
                    }

                    Storyboard.SetTarget(storyBoard, rune);
                    Storyboard.SetTargetProperty(daX, new PropertyPath(Canvas.TopProperty));
                    Storyboard.SetTargetProperty(daY, new PropertyPath(Canvas.LeftProperty));
                    storyBoard.Children.Add(daX);
                    storyBoard.Children.Add(daY);

                    storyBoard.Begin();
                }
            }

            return maxDuration;
        }

        public static double GetDuration(RuneItemChangeInfo item, bool isOp)
        {
            int baseValue = GameStatics.RuneDownSpeed;
            if (isOp)
            {
                baseValue = 120;
            }
            double offset;
            int x = Math.Abs(item.StartX - item.EndX);
            int y = Math.Abs(item.StartY - item.EndY);
            if (x > 0 && y > 0)
            {
                offset = x * Math.Sqrt(2.0);
            }
            else
            {
                if (x > y)
                {
                    offset = x;
                }
                else
                {
                    offset = y;
                }
            }
            return baseValue * offset;
        }

        private object getCurrentRuneInfosSync = new object();

        /// <summary>
        /// 获取当前的符文信息（保存关卡信息）
        /// </summary>
        /// <returns></returns>
        internal List<SavedRune> GetCurrentRuneInfos()
        {
            lock (getCurrentRuneInfosSync)
            {
                try
                {
                    List<SavedRune> result = new List<SavedRune>();

                    for (int i = 0; i < GameStatics.RowCount; i++)
                    {
                        for (int j = 0; j < GameStatics.ColumnCount; j++)
                        {
                            SavedRune runeRecord = new SavedRune();
                            runeRecord.X = i;
                            runeRecord.Y = j;
                            runeRecord.LeftSpriteCount = runes[i, j].GetSpriteAddLeftCount();
                            runeRecord.RuneType = datas[i, j];
                            result.Add(runeRecord);
                        }
                    }

                    return result;
                }
                catch
                {
                    return null;
                }
            }
        }

        internal void ReArrange()
        {
            spriteRunes.Clear();
            if (selectedItem != null)
            {
                selectedItem.UnSelect();
            }
            selectedItem = null;
            selectColumn = -1;
            selectRow = -1;

            //重新生成一遍Rune即可
            //初始化
            for (int i = 0; i < GameStatics.RowCount; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount; j++)
                {
                    datas[i, j] = 0;
                }
            }

            for (int i = 0; i < GameStatics.RowCount; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount; j++)
                {
                    //需要判断保证一开始不能有能直接消除的东西
                    RuneItem item = runes[i, j];
                    int type = r.Next(5) + 1;
                    datas[i, j] = type;
                    while (EliminateLogicHelper.IsCanEliminate(datas))
                    {
                        type = r.Next(5) + 1;
                        datas[i, j] = type;
                    }
                    item.SetType(type);
                    item.SetSpriteAddRune(0);
                    runes[i, j] = item;
                }
            }
        }

        internal void CollectAllSprite()
        {
            while (true)
            {
                lock (isElimitionSyncObj)
                {
                    if (!isElimition)
                    {
                        break;
                    }
                }
            }
            foreach (var item in spriteRunes)
            {
                if (item.IsSpriteAddRune())
                {
                    int baseValue = 1;
                    if (StageManager.Instance.CurrentUsedTool.ContainsValue(ToolType.SpriteMutil2))
                    {
                        baseValue = 2;
                    }
                    item.FlyAddSpriteFlag(baseValue);
                }
            }
            spriteRunes.Clear();
        }

        internal void CreateNewSpiritRune()
        {
            while (true)
            {
                lock (isElimitionSyncObj)
                {
                    if (!isElimition)
                    {
                        break;
                    }
                }
            }
            //增加2个精神力符文
            for (int i = 0; i < 2; i++)
            {
                int toolRow = r.Next(GameStatics.RowCount);
                int toolColumn = r.Next(GameStatics.ColumnCount);

                while (runes[toolRow, toolColumn].IsSpriteAddRune())
                {
                    toolRow = r.Next(GameStatics.RowCount);
                    toolColumn = r.Next(GameStatics.ColumnCount);
                }

                if (!runes[toolRow, toolColumn].IsSpriteAddRune())
                {
                    //设置成为精神力符文
                    runes[toolRow, toolColumn].SetSpriteAddRune();
                    spriteRunes.Add(runes[toolRow, toolColumn]);
                }
            }
        }
    }
}
